﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
namespace LitTools
{
    /// <summary>
    /// 自定义文件存档系统
    /// 依赖Newtonsoft.Json
    /// 可以使用AES加密
    /// 自定义文件IO
    /// </summary>
    public class CustomFileSave : SaveBehaviour
    {
        public string fileName = "saveData.veer";//存档文件名
        public Dictionary<string, string> dataDict;//缓存数据字典
        private bool useEncrypt;//使用加密
        public CustomFileSave(bool useEncrypt = true)
        {
            this.useEncrypt = useEncrypt;
        }

        public override void Init()
        {
            base.Init();
            dataDict = new Dictionary<string, string>();
            var path = Application.persistentDataPath + "/" + fileName;
            if (File.Exists(path))
            {
                StreamReader sr = new StreamReader(path);
                var str = sr.ReadToEnd();
                sr.Close();
                if (useEncrypt)
                    str = EncryptAndDecryptByAES.DecryptString(str);
                dataDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(str);
            }
        }
        public override T LoadData<T>()
        {
            T data = new T();
            if (dataDict.ContainsKey(data.SaveKey))
            {
                data = JsonConvert.DeserializeObject<T>(dataDict[data.SaveKey]);
            }
            else
                data = data.GetDefaultValue();
            return data;
        }

        public override void SaveData<T>(T data)
        {
            if (!dataDict.ContainsKey(data.SaveKey))
                dataDict.Add(data.SaveKey, "");
            dataDict[data.SaveKey] = JsonConvert.SerializeObject(data);
        }

        public override void WriteToDisk()
        {
            var path = Application.persistentDataPath + "/" + fileName;
            string value = JsonConvert.SerializeObject(dataDict);
            if (useEncrypt)
                value = EncryptAndDecryptByAES.EncryptString(value);
            StreamWriter sw;
            if (File.Exists(path))
            {
                sw = new StreamWriter(path);
            }
            else
            {
                FileStream fs = File.Create(path);
                sw = new StreamWriter(fs);
            }
            sw.Write(value);
            sw.Close();
        }
    }
}